import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET() {
  try {
    const sql = `
            SELECT 
                o.orderId, 
                o.openId, 
                o.goodsId, 
                o.createTime, 
                o.state, 
                o.goodsAD, 
                o.tel, 
                o.oName, 
                o.trading,
                u.uName,
                c.goodsName,
                c.goodsPrice,
                c.ImgUrl
            FROM 
                \`order\` o
            LEFT JOIN 
                \`user\` u ON o.openId = u.openId
            LEFT JOIN 
                \`commodity\` c ON o.goodsId = c.goodsId
            WHERE 
                o.goodsId IS NOT NULL;
        `;

    const orders = await prisma.$queryRawUnsafe(sql);

    // 格式化数据以匹配前端期望的结构，同时处理可能为null的情况
    const formattedOrders = orders.map((order: any) => ({
      orderId: order.orderId,
      openId: order.openId,
      goodsId: order.goodsId,
      orderTime: order.createTime ? order.createTime.toISOString() : "",
      orderState: order.state,
      goodsAddress: order.goodsAD,
      tel: order.tel,
      customerName: order.oName,
      trading: order.trading,
      userName: order.uName || "",
      goodsName: order.goodsName || "",
      goodsPrice: order.goodsPrice || 0,
      goodsImage: order.ImgUrl || "",
    }));

    return NextResponse.json({ orders: formattedOrders }, { status: 200 });
  } catch (error) {
    console.error("获取订单数据失败:", error);
    return NextResponse.json({ error: "获取订单数据失败" }, { status: 500 });
  }
}
